"use client"

import { useEffect, useRef, useState } from "react"
import { Camera, Play, Slash, ZoomIn, ZoomOut, Maximize2 } from "lucide-react"
import { tr } from "date-fns/locale"

interface CameraFeedProps {
  videoRef: React.RefObject<HTMLVideoElement | null> // 接收 videoRef 而非 URL
  type: "student" | "content"
  isActive: boolean
  className?: string
  isPrimary?: boolean
  pipMode?: boolean
  onSwitchCamera?: () => void
  networkError?: boolean
}

export function CameraFeed({
  videoRef,
  type,
  isActive,
  className,
  isPrimary = true,
  pipMode = false,
  onSwitchCamera,
  networkError: propNetworkError,
}: CameraFeedProps) {
  const [zoomLevel, setZoomLevel] = useState(1)
  const [internalError, setInternalError] = useState<string | null>(null)



  const handleZoom = (direction: "in" | "out" | "reset") => {
    if (direction === "in") {
      setZoomLevel((prev) => Math.min(prev + 0.25, 3))
    } else if (direction === "out") {
      setZoomLevel((prev) => Math.max(prev - 0.25, 0.5))
    } else {
      setZoomLevel(1)
    }
  }
  const [hasError, setHasError] = useState(false)
  useEffect(() => {
    const videoEl = videoRef.current;
    if (videoEl) {
      console.log("【DEBUG】videoEl.readyState:", videoEl.readyState);
      console.log("【DEBUG】videoEl.error:", videoEl.error);
      console.log("【DEBUG】videoEl.paused:", videoEl.paused);
      console.log("【DEBUG】videoEl.src:", videoEl.src);
    }
  }, [videoRef]);


  return (
    <div
      className={`relative ${className} overflow-hidden ${
        !pipMode && isPrimary ? "cursor-pointer" : ""
      }`}
    >
      {isActive && !hasError ? (
        <>
          {/* 使用传入的 videoRef，不再依赖 src */}
          <video
            ref={videoRef}
            muted
            autoPlay
            playsInline
            controls
            className="w-full h-full object-cover transition-transform duration-200"
            style={{ transform: isPrimary ? `scale(${zoomLevel})` : "none" }}
          />

          {!pipMode && (
            <div className="absolute top-2 right-2 bg-green-500/80 text-white text-xs px-2 py-1 rounded-full flex items-center">
              <div className="w-2 h-2 bg-white rounded-full mr-1 animate-pulse"></div>
              实时监控中
            </div>
          )}

          {isPrimary && !pipMode && isActive && (
            <div className="absolute top-2 left-2 flex items-center gap-2 bg-black/30 rounded-md p-2 text-white">
              <button
                onClick={(e) => {
                  e.stopPropagation()
                  handleZoom("out")
                }}
                className="p-1.5 rounded-md hover:bg-white/20 transition-colors"
                title="缩小"
              >
                <ZoomOut className="w-5 h-5" />
              </button>
              <div className="min-w-[48px] text-center font-medium">
                {Math.round(zoomLevel * 100)}%
              </div>
              <button
                onClick={(e) => {
                  e.stopPropagation()
                  handleZoom("in")
                }}
                className="p-1.5 rounded-md hover:bg-white/20 transition-colors"
                title="放大"
              >
                <ZoomIn className="w-5 h-5" />
              </button>
              <button
                onClick={(e) => {
                  e.stopPropagation()
                  handleZoom("reset")
                }}
                className="p-1.5 rounded-md hover:bg-white/20 transition-colors ml-1"
                title="重置缩放"
              >
                <Maximize2 className="w-5 h-5" />
              </button>
            </div>
          )}
        </>
      ) : (
        <div className="absolute inset-0 flex items-center justify-center bg-muted">
          {hasError ? (
            <div className="text-center text-destructive">
              <Slash className="w-12 h-12 mx-auto mb-2" />
              {!pipMode && <p>视频流异常，请检查网络连接</p>}
            </div>
          ) : (
            <div className="text-center">
              <Play className="w-12 h-12 mx-auto mb-2 text-muted-foreground" />
              {!pipMode && <p className="text-muted-foreground">点击"开始监控"按钮启动摄像头</p>}
            </div>
          )}
        </div>
      )}

      {pipMode && (
        <div className="absolute inset-0 bg-black/40 opacity-0 hover:opacity-100 transition-opacity flex items-center justify-center">
          <div className="text-white text-xs font-medium">点击切换</div>
        </div>
      )}
    </div>
  )
}